#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
请求模块数据模型
"""

from datetime import datetime
from bson import ObjectId

class RequestDefinitionModel:
    """请求定义模型"""
    
    def __init__(self, definition_id=None, name=None, description=None, request_method=None, 
                 request_url=None, request_headers=None, request_body=None):
        self.id = str(ObjectId()) if definition_id is None else definition_id
        self.name = name
        self.description = description
        self.request_method = request_method
        self.request_url = request_url
        self.request_headers = request_headers or {}
        self.request_body = request_body
        self.created_at = datetime.utcnow()
        self.updated_at = datetime.utcnow()
        
    def to_dict(self):
        """转换为字典"""
        return {
            "_id": self.id,
            "name": self.name,
            "description": self.description,
            "request_method": self.request_method,
            "request_url": self.request_url,
            "request_headers": self.request_headers,
            "request_body": self.request_body,
            "created_at": self.created_at,
            "updated_at": self.updated_at
        }
    
    @classmethod
    def from_dict(cls, data):
        """从字典创建对象"""
        if not data:
            return None
        
        definition = cls(
            definition_id=data.get("_id"),
            name=data.get("name"),
            description=data.get("description"),
            request_method=data.get("request_method"),
            request_url=data.get("request_url"),
            request_headers=data.get("request_headers", {}),
            request_body=data.get("request_body")
        )
        definition.created_at = data.get("created_at", datetime.utcnow())
        definition.updated_at = data.get("updated_at", datetime.utcnow())
        return definition
